//
//  LikeRecommendedViewController.m
//  Molian
//
//  Created by 胡津 on 4/6/2015.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "LikeRecommendedViewController.h"
#import "ArticleCell.h"
#import "ArticleViewController.h"

// 每次拉取的用户数目
#define LoadDataCount 30
@interface LikeRecommendedViewController ()<UITableViewDelegate,UITableViewDataSource>
//视图列表

@property (nonatomic, strong)NSMutableArray *likeArticles;
@property (nonatomic, strong)Utils *uview;

@end

@implementation LikeRecommendedViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.∂
    self.title = @"喜欢的推荐";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
     self.tableView.frame = CGRectMake(0, 0, DeviceWidth, DeviceHeight);
    self.likeArticles = [NSMutableArray array];
    self.uview = [[Utils alloc]init];
    [_uview viewControllerPrompt:self.view.bounds Text:@"还没有喜欢的推荐" Image:[UIImage imageNamed:@"xinlianren_nul"]];
    [self.view addSubview:_uview.viewPrompt];
    if ([self.likeArticles count] == 0) {
        _uview.viewPrompt.hidden = NO;
    }else{
        _uview.viewPrompt.hidden = YES;
    }
    [self loadLikeArticlesData];
}
- (void)loadLikeArticlesData
{
    // 获取喜欢过的文章记录
    AVQuery *articleLikeQuery = [MLArticleLike query];
    [articleLikeQuery includeKey:@"article"];
    [articleLikeQuery whereKey:@"user" equalTo:[MLUser currentUser]];
    articleLikeQuery.limit = LoadDataCount;
    articleLikeQuery.skip = self.currentPage *LoadDataCount;
    [articleLikeQuery orderByDescending:@"updatedAt"];
    articleLikeQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    articleLikeQuery.maxCacheAge = 7200;
    [HUD setOnViewWithTitle:@"加载中" animated:YES];
    
    [articleLikeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        [self.tableView footerEndRefreshing];
        [self.slimeView endRefresh];
        [HUD hideFromViewAnimated:YES];
        if (!error) {
            
            if (self.currentPage == 0) {
                [self.likeArticles removeAllObjects];
            }
            for (MLArticleLike *obj in objects) {
                [self.likeArticles addObject:obj];
            }
            if ([self.likeArticles count] == 0) {
                _uview.viewPrompt.hidden = NO;
            }else{
                _uview.viewPrompt.hidden = YES;
            }
            
            for (int i = 0; i<self.likeArticles.count; i++) {
                MLArticleLike *userLike = [self.likeArticles objectAtIndex:i];
                [Utils savePassLoveArticleObjectID:userLike.article.objectId];
                for (int j = i+1; j<self.likeArticles.count; j++) {
                    MLArticleLike *nUserLike = [self.likeArticles objectAtIndex:j];
                    if ([userLike.article.objectId isEqualToString:nUserLike.article.objectId]) {
                        [self.likeArticles removeObjectAtIndex:j];
                        [nUserLike deleteInBackground];
                        j--;
                    }
                }
            }
            [self.tableView reloadData];
            self.currentPage++;
        }
    }];
}
//上拉
- (void)upPullLoadData
{
    if(self.likeArticles.count<LoadDataCount/2){
        [self.tableView footerEndRefreshing];
        return;
    }
    [self loadLikeArticlesData];
}
//下拉
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    //加载数据
    self.currentPage = 0;
    [self loadLikeArticlesData];
}



#pragma mark - tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO 分页加载文章
    static NSString *cellIdentifier = @"ArticleCell" ;
    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if  (cell == nil) {
        cell = [[ArticleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.tabbar = self.tabBarController;
        
    }
    
    // 如果文章列表为空则返回空cell
    if (self.likeArticles.count == 0) {
        return cell;
    }
    
    MLArticleLike *articleLike = self.likeArticles[indexPath.row];
    MLArticle *article = (MLArticle *)articleLike.article;
    
    cell.article = article;
    cell.parentViewController = self;
    
    // 异步加载图片
    [cell.titleImage sd_setImageWithURL:[NSURL URLWithString:article.title_img.url] placeholderImage:[UIImage imageNamed:@"common_image_loading"]];
    cell.titleLabel.text = article.title;
    NSString *likeStr = [[ShareData shareData].likeArticlesDic objectForKey:article.objectId];
    cell.likeBtn.Title.text = likeStr;
    [cell.likeBtn layoutSubviews];
    if ([Utils inspectArticleReadObjectID:article.objectId]) {
        cell.nImageView.hidden = YES;
    }else{
        cell.nImageView.hidden = NO;
    }
    [cell.likeBtn removeFromSuperview];

    return  cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MLArticleLike *articleLike = self.likeArticles[indexPath.row];
    MLArticle *article = (MLArticle *)articleLike.article;
    
    // 跳转到文章页面
    ArticleViewController *articleViewController = [[ArticleViewController alloc]init];
    articleViewController.article =article;
   
    articleViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:articleViewController animated:YES];
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.likeArticles count];
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return EqualHeight(260, 608, DeviceWidth-20)+8;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

@end
